import type { FC, ReactNode } from 'react'
import React, { memo, useEffect } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import {
  EyeInvisibleOutlined,
  EyeTwoTone,
  LockOutlined,
  UserOutlined
} from '@ant-design/icons'
import { Button, Checkbox, Form, Input } from 'antd'

import { useMyDispatch, useMySelector } from '@/store'
import { PasswordWrapper } from '@/views/login/c-cpns/password-pannel/style'
import { fetchLoginAction, fetchVerifyCodeAction } from '@/store/module/login'
import { encryptData } from '@/utils/encrypt'
import useEncrypt from '@/hooks/use-encrypt'
import { ILoginStatus } from '@/global/type'
import { localCache } from '@/utils/cache'
import { CacheType } from '@/global/constant'

interface IProps {
  children?: ReactNode
}

enum GetOrSetLoginStatus {
  Get,
  Set
}

enum FormProps {
  UserName = 'userName',
  Password = 'password',
  Flag = 'flag'
}

const PasswordPannel: FC<IProps> = (props) => {
  /** 数据 **/
  const [passwordForm] = Form.useForm()
  const dispatch = useMyDispatch()
  const navigate = useNavigate()
  const [publicKey] = useEncrypt()
  const { code } = useMySelector((state) => ({
    code: state.login.code
  }))

  /** 逻辑 **/
  useEffect(() => {
    // 初次请求验证码
    dispatch(fetchVerifyCodeAction())
    // 从本地加载用户状态
    handleLoginStatus(GetOrSetLoginStatus.Get)
  }, [])

  /** 回调 **/
  // 提交表单的逻辑
  const onFinish = (values: any) => {
    // 用公钥去加密参数
    !values.flag && (values.flag = false)
    const newValues = { ...values, loginType: 'pc', loginMethod: 0 }
    console.log(newValues)
    const loginParams = encryptData(publicKey, newValues)

    // 准备去登录
    if (loginParams) {
      dispatch(fetchLoginAction(loginParams)).then(() => {
        // 进行路由跳转
        navigate('/main', { replace: true })
        // 登陆成功判断是否需要记住密码
        handleLoginStatus(GetOrSetLoginStatus.Set, values)
      })
      // 登录就刷新验证码
      dispatch(fetchVerifyCodeAction())
    }
  }

  // 更换图片验证码
  function handleCodeClick() {
    dispatch(fetchVerifyCodeAction())
  }

  // 处理本地账号密码：获取或者设置
  function handleLoginStatus(type: GetOrSetLoginStatus, values?: any) {
    // 设置登录账号密码在本地
    if (type === GetOrSetLoginStatus.Set) {
      const { flag, userName, password } = values
      let loginStatus: ILoginStatus = { flag }
      if (flag) {
        loginStatus = { ...loginStatus, userName, password }
      }
      localCache.setCache(CacheType.LOGIN_STATUS, loginStatus)
    }
    // 从本地获取登录账号密码
    if (type === GetOrSetLoginStatus.Get) {
      const loginStatus = localCache.getCache(CacheType.LOGIN_STATUS)
      // 用户第一次登录网址，应该设置表单为空
      if (!loginStatus) {
        passwordForm.setFields([
          { name: FormProps.UserName, value: '' },
          { name: FormProps.Password, value: '' },
          { name: FormProps.Flag, value: '' }
        ])
        return
      }
      // 用户后面再进去网站直接获取本地数据
      const { flag, userName, password } = loginStatus
      if (flag) {
        passwordForm.setFields([
          { name: FormProps.UserName, value: userName },
          { name: FormProps.Password, value: password },
          { name: FormProps.Flag, value: flag }
        ])
      }
    }
  }

  return (
    <PasswordWrapper>
      <Form
        name="password_login"
        form={passwordForm}
        initialValues={{ remember: true }}
        onFinish={onFinish}
      >
        <Form.Item
          name="userName"
          rules={[{ required: true, message: '请输入用户名！' }]}
        >
          <Input
            prefix={<UserOutlined className="site-form-item-icon" />}
            placeholder="用户名"
          />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: '请输入密码!' }]}
        >
          <Input.Password
            prefix={<LockOutlined />}
            placeholder="密码"
            iconRender={(visible) =>
              visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />
            }
          />
        </Form.Item>
        <Form.Item
          name="code"
          rules={[{ required: true, message: '请输入验证码！' }]}
        >
          <div className="code-wrapper">
            <Input placeholder="验证码" />
            <img
              className="code"
              src={code}
              alt=""
              onClick={handleCodeClick}
            ></img>
          </div>
        </Form.Item>
        <Form.Item>
          <div className="other">
            <Form.Item name="flag" valuePropName="checked" noStyle>
              <Checkbox>记住我</Checkbox>
            </Form.Item>
            <Link to="/forget-pwd" target="_blank">
              忘记密码?
            </Link>
          </div>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
            登录
          </Button>
        </Form.Item>
      </Form>
    </PasswordWrapper>
  )
}

export default memo(PasswordPannel)
